﻿namespace MsdnWeb

open System
open Newtonsoft.Json
open SignalR

module MPI =
    
    (* Alias MailboxProcessor with Agent *)
    type Agent<'a> = MailboxProcessor<'a>
    type Numbers = {num1: string; num2: string;}
    type Msg = | Req of string * PersistentConnection
    let agent() =
        new Agent<Msg>(fun inbox ->
                            let rec loop message = 
                                    async {
                                            let! message = inbox.Receive()
                                            match message with
                                            | Req(v,conn) -> 
                                                let numbers = JsonConvert.DeserializeObject<Numbers>(v)        
                                                let work_recieved = sprintf "recieved numbers %s and %s" numbers.num1 numbers.num2
                                                conn.Connection.Broadcast(work_recieved) |> ignore //notify the client what work we have recieved                     
                                                let r  = (numbers.num1 |> int) + (numbers.num2 |> int) //do the work!! simple addition operation    
                                                conn.Connection.Broadcast(r) |> ignore // notify the result back to the client

                                            return! loop() } 
                            loop())
       
